package com.example.clickgame;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	private TextView second, count;
	private Button click;
	private int countNum;
	private Handler handler;
	private Timer timer;
	private TimerTask task;
	private int time;
	private static final int REQUEST_CODE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		startGame();
	}

	public void initView() {
		second = (TextView) findViewById(R.id.second);
		count = (TextView) findViewById(R.id.count);
		click = (Button) findViewById(R.id.click_bt);
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					second.setText(timeFormat());
					if (time == 0) {
						task.cancel();
						click.setText("game over!!");
						Intent intent = new Intent(MainActivity.this,
								TransparentActivity.class);
						startActivityForResult(intent, REQUEST_CODE);
					}
				}

				super.handleMessage(msg);
			}
		};

	}

	public void startGame() {
		count.setVisibility(View.INVISIBLE);
		click.setText("click to start!");
		second.setText("10:00");
		time = 10000;
		countNum = 1;
		timer = new Timer();
		task = new TimerTask() {

			@Override
			public void run() {
				handler.sendEmptyMessage(0);
			}
		};
		click.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (time == 10000) {
					click.setText("Click Me!!");
					count.setVisibility(View.VISIBLE);
					timer.schedule(task, 0, 10);
				}
				if (time != 0) {
					count.setText(countNum + "");
					countNum++;
				}
			}
		});

	}

	public String timeFormat() {
		if((time -= 10)<0){
			time=0;
		}
		
		return "" + time / 10000 % 10 + time / 1000 % 10 + ":" + time / 100
				% 10 + time / 10 % 10;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
			if (data != null) {
				if (data.getDataString().equals("exit")) {
					MainActivity.this.finish();
				} else if (data.getDataString().equals("restart")) {
					startGame();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
